package club.itstudio.itouc.controller.jw.stu

import club.itstudio.itouc.core.exception.ITOUCException
import club.itstudio.itouc.core.util.Result
import club.itstudio.itouc.core.util.ResultUtil
import club.itstudio.itouc.jw.ParamsBuilder
import club.itstudio.itouc.jw.Parser
import club.itstudio.itouc.service.JwOps
import club.itstudio.itouc.util.Redis
import org.springframework.web.bind.annotation.CookieValue
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class Score (val jwOps: JwOps,
             val parser: Parser,
             val jw: ParamsBuilder,
             val redis: Redis){

    @GetMapping("/jw/stu/score")
    fun getScore(@CookieValue token: String): Result<Any> {
        val session = jwOps.getJwSession(token)
        return try {
            val map = redis.getScore(session.userCode)
            val time = map["time"] as Long
            val now = System.currentTimeMillis()

            if ((now - time)  > 60 * 60 * 1000) {
                // 旧数据超过一小时更新数据
                jwOps.updateScore(session)
            }
            val scoreList = map["scores"]
            ResultUtil.success(scoreList)
        }catch (e: ITOUCException) {
            session.refresh()
            val scoreList = jwOps.getScoreList(session)
            redis.saveScore(session.userCode, scoreList)
            ResultUtil.success(scoreList)
        }
    }
}